<?php

namespace Aitels\Foundation\Generate;

use Illuminate\Filesystem\Filesystem;
use Illuminate\Support\Str;

class Writer
{
    protected $fileSystem;

    public function __construct()
    {
        $this->fileSystem = new Filesystem();
    }

    public function write($realPath, $content, $overWritten = false)
    {
        if ($this->alreadyExists($realPath) && !$overWritten) {

            $originalContent = $this->fileSystem->get($realPath);
            if ($originalContent !== $content) {
                $path = Str::after($realPath, base_path());
                if ($command = app()->genCommand) {
                    $command->warn($path.' already exists , skipped .');
                } else {
                    echo $path.'already exists , not changed .'.PHP_EOL;
                }
            }
            return false;
        } else {
            $this->createDirectoryIfNecessary($realPath);
            $originalContent = $this->fileSystem->exists($realPath) ? $this->fileSystem->get($realPath) : null;
            $createdOrUpdated = $originalContent ? ' updated.' : ' created.';


            if ($originalContent !== $content) {
                $this->fileSystem->put($realPath, $content);
                $realPath = Str::after($realPath, base_path());

                if ($command = app()->genCommand) {
                    $command->info($realPath.$createdOrUpdated);
                } else {
                    echo $realPath.$createdOrUpdated.PHP_EOL;
                }
            }
        }
    }


    protected function alreadyExists($realPath)
    {
        return $this->fileSystem->exists($realPath);
    }

    protected function createDirectoryIfNecessary($path)
    {
        if (!$this->fileSystem->isDirectory(dirname($path))) {
            $this->fileSystem->makeDirectory(dirname($path), 0777, true, true);
        }
    }


}
